import { Message, StorageData } from '../types/autoplayer';

let intervalId: number | null = null;
let settings: StorageData | null = null;
let notFoundCount = 0;
const MAX_NOT_FOUND = 3;

const log = (level: 'log' | 'warn' | 'error', ...args: any[]) => {
  console[level]('[AP-content]', ...args);
};

const sendMessage = (message: Message) => {
  try {
    chrome.runtime.sendMessage(message);
  } catch (e) {
    log('error', 'Failed to send message:', e);
  }
};

const findVideoElement = (selector?: string): HTMLVideoElement | null => {
  if (selector) {
    return document.querySelector(selector);
  }
  return document.querySelector('video');
};

const clickNextButton = () => {
  if (!settings) return;

  const video = findVideoElement(settings.videoSelector);
  const button: HTMLElement | null = document.querySelector(settings.buttonSelector);

  if (!video) {
    sendMessage({ type: 'error', payload: { error: new Error('Video element not found'), context: 'clickNextButton' } });
    return;
  }

  if (button && button.offsetParent !== null) {
    notFoundCount = 0;
    const remainingTime = video.duration - video.currentTime;
    if (remainingTime <= 5) { // Click when 5 seconds are left
      const lastTime = video.currentTime;
      button.click();
      log('log', 'Clicked next button');

      // Verify click was successful
      setTimeout(() => {
        if (video.currentTime <= lastTime) {
          log('warn', 'Video time did not advance after click, retrying...');
          button.click(); // Retry once
        }
      }, 500);
    }
  } else {
    notFoundCount++;
    log('warn', `Next button not found (attempt ${notFoundCount})`);
    if (notFoundCount >= MAX_NOT_FOUND) {
      sendMessage({ type: 'error', payload: { error: new Error('Next button disappeared'), context: 'clickNextButton' } });
      stopPlayer();
    }
  }
};

const startPlayer = (data: StorageData) => {
  settings = data;
  notFoundCount = 0;
  if (intervalId) {
    clearInterval(intervalId);
  }
  // The alarm from background script will trigger the check via 'tick' message.
  // We just set up a local interval for more frequent checks if needed, but rely on the alarm primarily.
  log('log', 'Player started');
};

const stopPlayer = () => {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
  settings = null;
  log('log', 'Player stopped');
};

chrome.runtime.onMessage.addListener((message: Message, sender, sendResponse) => {
  switch (message.type) {
    case 'start':
      startPlayer(message.payload);
      sendResponse({ status: 'running' });
      break;
    case 'stop':
      stopPlayer();
      sendResponse({ status: 'idle' });
      break;
    case 'tick':
      clickNextButton();
      break;
    case 'toggle':
        // Simple toggle logic, assumes popup manages state
        if (settings) {
            stopPlayer();
            sendMessage({ type: 'stop' }); // Inform background to stop alarms
        } else {
            // This is tricky, we don't have settings. Popup should initiate start.
            log('warn', "Toggle received but no settings available.");
        }
        break;
  }
  return true;
});

log('log', 'Content script loaded.');